package cn.power.win.win_power.acitivity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.power.win.win_power.fragment.LeftFragment;
import cn.power.win.win_power.fragment.NodeFragment;
import cn.power.win.win_power.utils.MyFragmentPagerAdapter;
import cn.power.win.win_power.R;
import cn.power.win.win_power.utils.PermissionsChecker;
import cn.power.win.win_power.utils.SpUtils;
import me.jessyan.autosize.AutoSizeCompat;
import me.jessyan.autosize.internal.CustomAdapt;


/**
 * 主页
 */
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener, CustomAdapt {

    //UI Objects
    private TextView txt_topbar;
    private RadioGroup rg_tab_bar;
    private RadioButton rb_channel;
    private RadioButton rb_message;
    private RadioButton rb_better;
    private RadioButton rb_setting;
    private ViewPager vpager;

    private MyFragmentPagerAdapter mAdapter;
    private static final String TAG_EXIT = "exit";

    //几个代表页面的常量
    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;
    public static final int PAGE_FOUR = 3;

    private RelativeLayout mRl_toolbar;
    private DrawerLayout mDrawerLayout;
    private LeftFragment mFg_left_menu;
    private Button mBtn_left;
    private Button mBtn_delete;
    public BluetoothAdapter mBluetoothAdapter;

    private android.support.v4.app.FragmentManager fManager;
//  private NodeFragment.MyReceiver mMyReceiver;
    public static final int MY_PERMISSION_REQUEST_CONSTANT = 12;
    private static final int REQUEST_ENABLE_BT = 1;
    private PermissionsChecker mPermissionsChecker;

  /*  @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONSTANT: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 运行时权限已授权
                }
                return;
            }
        }

    }
*/
    private final int RESULT_CODE_LOCATION = 0x001;
    //定位权限,获取app内常用权限
    String[] permsLocation = {"android.permission.READ_PHONE_STATE"
         /*   , "android.permission.ACCESS_COARSE_LOCATION"
            , "android.permission.ACCESS_FINE_LOCATION"
            , "android.permission.READ_EXTERNAL_STORAGE"
            , "android.permission.WRITE_EXTERNAL_STORAGE"*/};



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉标题栏
       // requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        initAdapter();
        //注册广播
        //创建广播接受类实例化对象
  /*    mMyReceiver = new NodeFragment.MyReceiver();
        IntentFilter intentFiltet = new IntentFilter();
        //设置广播的名字（设置Action，可以添加多个要监听的动作）
        intentFiltet.addAction("MyBroadCast");
        //注册广播,传入两个参数， 实例化的广播接受者对象，intent 动作筛选对象
        registerReceiver(mMyReceiver,intentFiltet);*/
        //动态添加权限
   /*     mPermissionsChecker = new PermissionsChecker(MainActivity.this);
        if (mPermissionsChecker.lacksPermissions(permsLocation)) {
            ActivityCompat.requestPermissions(MainActivity.this, permsLocation, RESULT_CODE_LOCATION);
        }*/


        mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        //获取fragment管理器
        fManager = getSupportFragmentManager();
        //初始化 侧滑LeftFragment
        mFg_left_menu = (LeftFragment) fManager.findFragmentById(R.id.fg_left_menu);
        //绑定界面
        bindViews();
        //模拟一次点击，既进去后选择第一项
        rb_channel.setChecked(true);

    }

    private void initAdapter() {
        // 获取BluetoothAdapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 判断是否支持蓝牙
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            Toast.makeText(this, "手机不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
        // 打开蓝牙
        if(!mBluetoothAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
        }
        checkBluetoothPermission();
    }

    private void checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //校验是否已具有模糊定位权限
            if (ContextCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        REQUEST_ENABLE_BT);
            } else {
                //具有权限

            }
        } else {
            //系统不高于6.0直接执行

        }
    }

    /*
    *  Activity 将会在 onActivityResult() 回调中收到 RESULT_OK 结果代码。
     *  如果由于某个错误（或用户响应“No”）而没有启用蓝牙，则结果代码为 RESULT_CANCELED。
    *
    *
    * */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //同意权限
                Toast.makeText(getApplicationContext(),"获取蓝牙权限成功",Toast.LENGTH_LONG).show();

            } else {
                // 权限拒绝
                Toast.makeText(getApplicationContext(),"没有蓝牙权限",Toast.LENGTH_LONG).show();
            }
        }
    }




    @Override
    protected void onStart() {
        super.onStart();
   /*     //  获取 从ManullyEnterActivity  传过来的数据
        String id = getIntent().getStringExtra("id");
        Log.e("id",id+"------");
        String code = getIntent().getStringExtra("code");
        Log.e("code",code+"------");
        if (id != null &&code != null) {
            if ("0".equals(id)) {
            // 发送标准广播
         *//*     Intent intent = new Intent("android.intent.action.CART_BROADCAST");
                intent.putExtra("data",code);
                LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
                sendBroadcast(intent);*//*

        *//*     Intent intent = new Intent("cn.power.win.win_power");
              intent.putExtra("data",code);
              LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);*//*


                NodeFragment nodeFragment = new NodeFragment();
                    // 绑定 参数
                    Bundle bundle = new Bundle();
               //   bundle.putSerializable("code",code);
                    bundle.putString("code",code);
                    nodeFragment.setArguments(bundle);
                     getSupportFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null) //将当前的fragment加入返回栈
                        .replace(R.id.vpager, nodeFragment)
                        .commit();

            }
        }*/
        //  注册EventBus
        //  EventBus.getDefault().register(this);
    }

    //UI组件初始化与事件绑定
    private void bindViews() {
        //
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mRl_toolbar = (RelativeLayout) findViewById(R.id.rl_toolbar);
        mBtn_left = (Button) findViewById(R.id.btn_left);
        mBtn_delete = (Button) findViewById(R.id.btn_Right);

        rg_tab_bar = (RadioGroup) findViewById(R.id.rg_tab_bar);
        rb_channel = (RadioButton) findViewById(R.id.rb_channel);
        rb_message = (RadioButton) findViewById(R.id.rb_message);
        rb_better = (RadioButton) findViewById(R.id.rb_better);
        rb_setting = (RadioButton) findViewById(R.id.rb_setting);
        rg_tab_bar.setOnCheckedChangeListener(this);

        //删除选中项
        mBtn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

             //   EventBus.getDefault().post(new MessageEvent("delete"));
            }
        });
        mBtn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开侧滑菜单
                mDrawerLayout.openDrawer(Gravity.START);
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.START);    //解除锁定
            }
        });
        //设置右面的侧滑菜单只能通过编程来打开(关闭手势滑动)
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.START);
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {

            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                        Gravity.START);
            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });
        //绑定布局
        mFg_left_menu.setDrawerLayout(mDrawerLayout);

        vpager = (ViewPager) findViewById(R.id.vpager);
        vpager.setAdapter(mAdapter);
        /*
        * 方法设置了在多个Fragment切换时，当前显示的Fragment左右两边最多保存几个Fragment的页面，默认值是1，也就是说当前页的左右各能保存一个页面。如果切换到了超过保存的页面上去，那么就要根据适配器需要而重新创建所需的Fragment。
        * 这个方法的存在意义是为了优化。特别是Fragment数目是已知的情况或者使用懒加载机制的情况。
        *
        * */
        vpager.setOffscreenPageLimit(3);
        vpager.setCurrentItem(0);
        vpager.addOnPageChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_channel:
                vpager.setCurrentItem(PAGE_ONE);
                mRl_toolbar.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_message:
                vpager.setCurrentItem(PAGE_TWO);
                mRl_toolbar.setVisibility(View.GONE);
                break;
            case R.id.rb_better:
                vpager.setCurrentItem(PAGE_THREE);
                mRl_toolbar.setVisibility(View.GONE);
                break;
            case R.id.rb_setting:
                vpager.setCurrentItem(PAGE_FOUR);
                mRl_toolbar.setVisibility(View.GONE);
                break;
        }
    }


    //重写ViewPager页面切换的处理方法
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
      //  Log.i("tag",position+"点击了");
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //state的状态有三个，0表示什么都没做，1正在滑动，2滑动完毕
        if (state == 2) {
            switch (vpager.getCurrentItem()) {
                case PAGE_ONE:
                    rb_channel.setChecked(true);
                    break;
                case PAGE_TWO:
                    rb_message.setChecked(true);
                    break;
                case PAGE_THREE:
                    rb_better.setChecked(true);
                    break;
                case PAGE_FOUR:
                    rb_setting.setChecked(true);
                    break;
            }
        }
    }



    // This method will be called when a MessageEvent is posted (in the UI thread for Toast)
  /*  //接受广播
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
       // Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
        if (event.getMessage()!= null) {
           *//* vpager.setCurrentItem(PAGE_TWO);
            mRl_toolbar.setVisibility(View.GONE);*//*
         *//*   mRl_toolbar.setVisibility(View.GONE);
                   getSupportFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null) //将当前的fragment加入返回栈
                        .replace(R.id.vpager,new ActualTimeFragment())
                        .commit();*//*

        }
    }*/

    @Override
    protected void onStop() {
        super.onStop();
        //取消注册
      //  EventBus.getDefault().unregister(this);
      //  unregisterReceiver(mMyReceiver);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
/*        SpUtils.putString(MainActivity.this, "Fan_unloading_current","");
        SpUtils.putString(MainActivity.this, "Fan_unloading_voltage", "");
        SpUtils.putString(MainActivity.this, "Fan_Stop_Speed", "");
        SpUtils.putString(MainActivity.this, "Fan_Begin_Charge_Voltage","");*/
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 670;
    }

    //暴露一个接口,给MyFragment中RecyclerView的点击事件使用.点击条目后从MyFragment1跳转到MyFragment2.
    public interface Fragment2Fragment{
        public void gotoFragment(ViewPager viewPager);
    }
    private  Fragment2Fragment fragment2Fragment;
    public void setFragment2Fragment(Fragment2Fragment fragment2Fragment){
        this.fragment2Fragment = fragment2Fragment;
    }

    public void forSkip(){
        if(fragment2Fragment!= null){
            fragment2Fragment.gotoFragment(vpager);
        }
    }
    //从MyFragment1跳转到MyFragment2并携带参数 在MainActivity里面写get（），set（）方法比如我们想点击时传递一个字符串
    private String name;
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }

    @Override
    public Resources getResources() {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
       // AutoSizeCompat.autoConvertDensityOfGlobal((super.getResources()));//如果没有自定义需求用这个方法
        AutoSizeCompat.autoConvertDensity((super.getResources()), 670, false);//如果有自定义需求就用这个方法
        return super.getResources();
    }

/*    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != ) {
            boolean isExit = intent.getBooleanExtra(TAG_EXIT, false);
            if (isExit) {
                this.finish();
            }
        }
    }*/

}
